package lt.marsrutai.mobile.android.fragment;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import lt.marsrutai.mobile.android.AppContext;
import lt.marsrutai.mobile.android.R;
import lt.marsrutai.mobile.android.activity.intent.NearestRoutesIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.RunStopsIntentHolder;
import lt.marsrutai.mobile.android.adapter.NextArrivalTimeAdapter;
import lt.marsrutai.mobile.android.exception.DataAccessException;
import lt.marsrutai.mobile.android.manager.ActivityManager;
import lt.marsrutai.mobile.android.model.ArrivalTime;
import lt.marsrutai.mobile.android.util.HourMinuteFormat;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockListFragment;

public class NextArrivalTimesFragment extends SherlockListFragment {

    private ActivityManager manager;

    private List<ArrivalTime> nextArrivalTimes;
    private ArrayAdapter<ArrivalTime> adapter;

    private String scopeFolder;
    private String stopName;
    private String stopFullName;
    private String stopDirectionName;
    private String stopId;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.list_fragment, null);
        ((TextView) view.findViewById(android.R.id.empty)).setText(R.string.next_arrivals_not_found);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        manager = new ActivityManager(getActivity());
        manager.showDownloadLoadingBar();

        receiveItemData();

        adapter = new NextArrivalTimeAdapter(getActivity(), scopeFolder);
        setListAdapter(adapter);

        downloadData();
    }
    
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        sendItemData(position);
    }

    public void receiveItemData() {
        NearestRoutesIntentHolder intentHolder = new NearestRoutesIntentHolder(getArguments());
        scopeFolder = intentHolder.getScopeFolder();
        stopName = intentHolder.getStopName();
        stopFullName = intentHolder.getStopFullName();
        stopId = intentHolder.getStopId();
        stopDirectionName = intentHolder.getStopDirectionName();
    }
    
    public void sendItemData(int i) {
        ArrivalTime time = nextArrivalTimes.get(i);               
        RunStopsIntentHolder intentHolder = new RunStopsIntentHolder(getActivity());
                       
        intentHolder.setScopeFolder(scopeFolder);
        intentHolder.setScopeName(null);        
        intentHolder.setTransportId(time.getTransportId());        
        intentHolder.setScheduleId(time.getScheduleId());
        intentHolder.setScheduleName(time.getScheduleName());
        intentHolder.setScheduleTrackName(null);
        intentHolder.setTrackId(time.getTrackId());
        intentHolder.setTrackName(null);
        intentHolder.setStopId(time.getStopId());
        intentHolder.setStopName(time.getStopName());
        intentHolder.setStopDirectionName(time.getStopDirectionName());                
        intentHolder.setRunId(time.getRunId());
        intentHolder.setScheduledTime(HourMinuteFormat.format(time.getScheduledTime()));
        
        startActivity(intentHolder.getIntent());
    }

    public void downloadData() {
        Runnable downloadTask = new Runnable() {

            @Override
            public void run() {
                getArrivalTimes(scopeFolder, stopFullName, stopDirectionName);
            }
        };
        Thread thread = new Thread(downloadTask);
        thread.start();
    }

    protected void getArrivalTimes(String scope, String stopName, String directionName) {
        try {
            // TODO move conversions a layer down
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
            String currentDateAndTime = sdf.format(Calendar.getInstance().getTime());
            
            nextArrivalTimes = AppContext.getDataService().getArrivalTimes(scope, stopId, stopName, 1440, 100, currentDateAndTime);
        }
        catch (DataAccessException e) {
            manager.runOnUiThread(manager.errorRes);
            return;
        }
        manager.runOnUiThread(returnRes);
    }

    private Runnable returnRes = new Runnable() {

        @Override
        public void run() {
            if (nextArrivalTimes != null && nextArrivalTimes.size() > 0) {
                for (int i = 0; i < nextArrivalTimes.size(); i++) {
                    adapter.add(nextArrivalTimes.get(i));
                }
            }
            manager.dismissDownloadLoadingBar();
        }
    };

}
